<template>

    <div id='share-content'>
        <div id='share-top'>
            <span>muke micro cloud</span>
        </div>
        <div id="share-main-content">
            <el-card class="box-card">
                <div slot="header" class="clearfix">
                    <div class="block" style="">
                        <span><b>{{this.shareName}} &nbsp;</b></span>
                    </div>
                    <div style="width:210px;line-height: 50px;float:left;">
                        <span style="float:left;">共 {{this.tableData.length}} 项</span>
                        <span style="float:left;" v-if="this.selectedData.length !== 0"> , 已选 {{this.selectedData.length}} 项 &nbsp;&nbsp;</span>
                        <el-row style="float:left;" v-if="this.selectedData.length !== 0">
                            <el-button @click="openSave" v-if="this.uid!=this.loginInfo.id" round size="medium">保存</el-button>
                        </el-row>
                        
                    </div>
                    
                    <div class="block" style="width:300px;float:right;">
                        <div style="float:left;width:110px;">
                            <el-row >
                                <el-button @click="deleteShare" v-if="this.uid==this.loginInfo.id" type="primary" round size="medium">取消分享</el-button> &nbsp; 
                            </el-row>
                        </div>
                        <span id='unlogin' @click="loginVisible = true" v-if="!isLogin" style="float:right;" >未登录?</span>
                        <div id='login' v-if="isLogin">
                            <div style="width:70px;height:60px;float:left;">
                                <el-popover
                                    placement="top-start"
                                    title="用户中心"
                                    width="200"
                                    trigger="hover">
                                    <div id="muke-list-content">
                                        <ul class="nav nav-pills nav-stacked">
                                            <!-- <li class="active"><a href="#">全部文件</a></li> -->
                                            <li  @click="myNetPan"><a>
                                                <i class="el-icon-s-home"></i> 我的网盘</a>
                                            </li>
                                            <!-- <li><a>
                                                <i class="el-icon-user"></i> 我的信息</a>
                                            </li> -->
                                            <li><a @click="logout">
                                                <i class="el-icon-switch-button"></i> 退出登录</a>
                                            </li>
                                        </ul>
                                    </div>
                                    <el-avatar slot="reference" id='shareAvatar' :size="50" :src="this.loginInfo.avatar"></el-avatar>
                                </el-popover>
                            </div>
                            <div style="width:60px;float:left;">
                                <span><b>{{this.loginInfo.nickname}}</b></span>
                            </div>
                        </div>
                    </div>
                    <div style="clear:both;">
                        <el-button @click="backFolder" v-if="fileShareInfo.currentId != -1" size="mini" icon="el-icon-back" circle></el-button>
                        <span id='share-title'> &nbsp;{{this.fileShareInfo.name}}</span>
                    </div>
                    
                </div>
                <div>
                    <el-table
                        ref="multipleTable"
                        :data="tableData"
                        tooltip-effect="dark"
                        style="width: 100%"
                        max-height="370"
                        @selection-change="handleSelectionChange"
                        >
                        <el-table-column
                            type="selection"
                            width="55">
                        </el-table-column>
                        <el-table-column
                            label="文件名"
                            width="200"
                            show-overflow-tooltip>
                        <template slot-scope="scope" >
                            <div @click="enterFolder(scope.row)" id='filename'>
                                <fileIcon id="icon" :file="scope.row" ></fileIcon>
                                <span style="line-height:40px;padding-left:10px;">{{ scope.row.name }}</span>
                            </div>
                        </template>
                        </el-table-column>
                        <el-table-column
                            prop="fileSize"
                            label="文件大小"
                            width="160"
                            show-overflow-tooltip>
                        </el-table-column>
                        <el-table-column
                            prop="updateTime"
                            label="更新时间"
                            show-overflow-tooltip>
                        </el-table-column>
                        <el-table-column
                            align="right"  style="width:100">
                            <template slot-scope="scope" v-if="scope.row.type === 'file'">
                                <el-button
                                size="mini"
                                @click="download(scope.row)">下载</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
            </el-card>
            <!-- 分享界面的登录对话框 -->
            <el-dialog title="muke micro cloud login" :visible.sync="this.loginVisible" :showClose="false">
                <el-form :model="user" :rules="rules" ref="user" >
                    <el-form-item label="邮箱"  prop="mail"  required>
                        <el-input type='text' v-model="user.mail" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="密码"  prop="pwd"  required>
                        <el-input type='password' v-model="user.pwd" autocomplete="off"></el-input>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="loginVisible = false" >取 消</el-button>
                    <el-button type="primary" :loading="loading" @click="login('user')">{{ loading ? '登录中 ...' : '登 录' }}</el-button>
                </div>
            </el-dialog>

            <!-- 目录树选择对话框 -->
            <el-dialog
                title="选择保存路径"
                :visible.sync="saveVisible"
                width="30%"
                :before-close="clearTree"
                :close-on-click-modal="false">
            
                <div id='file-tree'>
                    <el-tree
                        :data="data"
                        :load="loadNode"
                        :lazy="true"
                        :highlight-current="true"
                        accordion
                        @node-click="selectNode">
                        <span class="custom-tree-node" slot-scope="{ node }">
                            <span>
                                <i :class="icon2"></i> {{ node.label }}
                            </span>              
                        </span>
                    </el-tree>
                </div>
                <p v-if="nodeSelect">当前选中的文件夹 : 
                    <span style="color:red;">{{selectedFolderName}}</span> 
                </p>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="clearTree">关 闭</el-button>
                    <el-button type="primary" :loading="loading"
                        @click="saveFile">{{loading ? '保 存 中':'保 存'}}</el-button>
                </span>
            </el-dialog>
        </div>

    </div>
    
</template>


<script>
import util from '../../utils/util';
import fileIcon from '../../components/icons/file-icon';
import { error, fireEvent } from 'highcharts';
export default {
    components:{
        fileIcon
    },
    mounted(){
        this.validateLogin();
        this.initShareData();
    },
    data() {
      return {
        tableData: [],
        selectedData:[],
        multipleSelection: [],
        shareId:-1,
        shareName:'',
        isLogin:true,
        uid:-1,
        loginInfo:{},
        fileShareInfo:{pid:-1,currentId:-1,name:'文件列表'},
        fileRootIds:[],
        loginVisible:false,
        user:{mail:'',pwd:''},
        loading:false,
        rules: {
          mail: [
            { required: true, message: '请输入邮箱', trigger: 'blur' },
            { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
          ],
          pwd: [
            { required: true, message: '请输入密码', trigger: 'blur' },
            { min: 6, max: 20, message: '长度在 6 到 20个字符', trigger: 'blur' }
          ]
        },
        saveVisible: false,
        data: [{
                    label: '全部文件',
                    children: [{
                        label: '一级 1',
                        children: [{
                            label: '二级 1-1'
                        }]
                    }, {
                        label: '一级 2',
                    }, {
                        label: '一级 3',
                    }, {
                        label: '一级 4',
                    }, {
                        label: '一级 5',
                    }, {
                        label: '一级 6',
                    }, {
                        label: '一级 7',
                    }]
                }],
        nodeSelect:false,
        selectedFolderName:'全部文件',
        selectedFolderId:0,
        icon2:'el-icon-folder',
      }
    },
    methods:{
        handleSelectionChange(data){
            this.selectedData = data;
        },
        // 校验用户是否登录
        validateLogin() {
            this.$axios.get(util.API_HOST + '/user/myInfo')
            .then(response => {
                let result = response.data;
                if(result.code === 200) {
                    this.isLogin = true;
                    this.loginInfo = result.data;
                } else {
                    this.isLogin = false;
                }
            }).catch(err => {

            })
        },
        // 初始化分享数据
        initShareData() {
            this.$axios.get(util.API_HOST + '/file/share/query/url?url=' 
                + this.$route.params.name)
            .then(response => {
                let result = response.data;
                if(result.code === 200){
                    this.shareId = result.data.id;
                    this.shareName = result.data.shareName;
                    util.dataConvert(this.tableData, result.data.fileList);
                    this.uid = result.data.fileList[0].uid;
                    for (let file of result.data.fileList) {
                        this.fileRootIds.push({id:file.id,type:file.type});
                    }
                } else {
                    this.$router.push('/share/'+this.$route.params.name);
                }
            }).catch(err => {

            });
        },
        // 下载文件
        download(file) {
            location.href = util.API_HOST+'/file/file/download/file?id=' + file.id;
        },
        // 进入文件夹
        enterFolder(row){
            if(row.type === 'folder'){
                
                this.$axios.post(util.API_HOST + '/file/folder/query/share',{
                    pid:row.id,
                    uid:this.uid
                }).then(response => {
                    let result = response.data;
                    // 数据转换
                    if(result.code === 200){
                        this.fileShareInfo.pid = row.pid;
                        this.fileShareInfo.currentId = row.id;
                        this.fileShareInfo.name = row.name;
                        util.dataConvert(this.tableData, result.data);
                    }
                }).catch(err => {


                });

            }
        },
        // 返回上一级目录
        backFolder(){
            // 判断上一级是否为顶级目录
            for (let file of this.fileRootIds) {
                if(file.id===this.fileShareInfo.currentId && file.type==='folder') {
                    this.fileShareInfo.pid = -1;
                    this.fileShareInfo.currentId = -1;
                    this.fileShareInfo.name = '文件列表';
                    this.initShareData();
                    return;
                }
            }
            // 非顶级目录
            this.$axios.post(util.API_HOST + '/file/folder/query/share',{
                pid:this.fileShareInfo.pid,
                uid:this.uid
            }).then(response => {
                let result = response.data;
                if(result.code === 200){
                    this.fileShareInfo.currentId = this.fileShareInfo.pid;
                    util.dataConvert(this.tableData, result.data);
                    // 获取上一级目录的基本信息
                    this.$axios.post(util.API_HOST + '/file/folder/getFolder/share',{
                        id:this.fileShareInfo.pid
                    }).then(response => {
                        let result = response.data;
                        if(result.code === 200){
                            this.fileShareInfo.pid = result.data.parentFolderId;
                            this.fileShareInfo.name = result.data.folderName;

                        }
                    }).catch(err => {

                    });
                }
            }).catch(err => {

            });

        },
        login(formName){
            this.$refs[formName].validate((valid) => {
                // 获取user对象
                let user = this.$refs[formName].model;
                if (valid) {
                    this.loading = true;
                    // 前端校验成功
                    // 发送http请求
                    this.$axios.post(util.API_HOST + '/user/userLogin',
                    {
                        email:user.mail,
                        password:user.pwd
                    }).then(response =>{
                        let result = response.data;
                        if(result.code == 200){
                            // 成功
                            this.validateLogin();
                            this.loginVisible = false;
                            this.$notify.success({
                                title: 'success',
                                message: '登录成功'
                            });
                        } else {
                            this.$notify.error({
                                title: 'error',
                                message: result.message
                            });
                        }
                        this.loading = false;
                    }).catch(err => {
                        this.$notify.error({
                            title: 'error',
                            message: err.message
                        });
                        this.loading = false;
                    })
                    
                } else {
                    // 校验不通过
                    return false;
                }
            });
        },
        // 退出登录操作
        logout(){
            this.$confirm('是否退出登录?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
            // 发起退出登录请求
            this.$axios.post(util.API_HOST + '/user/logout',{
            }).then(response => {
                let result = response.data;
                if (result.code === 200){
                    this.loginInfo = {};
                    this.isLogin = false;
                    
                } else {
                    // 退出失败
                    this.$notify.error({
                        title:'退出失败',
                        message:result.message
                    });
                }
            }).catch(err => {
                this.$notify.error({
                title:'退出异常',
                message:err.message
                })
            });
            }).catch(() => {});
        },
        // 打开保存文件对话框
        openSave(){
            if(!this.isLogin) {
                this.loginVisible = true;
                return;
            }
            this.saveVisible = true;
        },
        // 目录树懒加载子节点
        loadNode(node, resolve) {
            if(node.level === 0) {
                let obj = {label:'全部文件',id:-1};
                resolve([obj]);
                return;
            } 
            let pid = node.data.id;
            this.$api.post('/file/folder/query/folders',{pid})
            .then(response => {
                let result = response.data;
                
                if(result.code === 200) {
                    
                    resolve(result.data);
                }
            }).catch();
        },
        // 点击选择树节点
        selectNode(obj, node, self){
            //console.log(obj);
            this.nodeSelect = true;
            this.selectedFolderName = obj.label;
            this.selectedFolderId = obj.id;

        },
        // 清除树
        clearTree(){
            this.saveVisible = false;
            this.nodeSelect = false;
            this.selectedFolderName = '全部文件';
            this.selectedFolderId = 0;
            this.data = [{label:'全部文件',id:-1}];
        },
        // 保存文件
        saveFile(){
            if(this.selectedFolderId === 0) {
                this.$notify.error('请选择文件夹');
                return;
            }
            let files = [];
            this.selectedData.forEach((file,index) => {
                files.push({
                    id: file.id,
                    name: file.name,
                    fileByte: file.fileByte,
                    fileType: file.fileType,
                    type: file.type,
                    pid: file.pid,
                    uid: file.uid,
                    actualId: file.actualId
                });
            });
            this.loading = true;
            this.$api.post("/file/share/save/share/files?folderId="
             + this.selectedFolderId, files)
            .then(response => {
                let result = response.data;
                this.loading = false;
                if(result.code === 200) {
                    this.$notify.success('文件保存成功');
                } else {
                    this.$notify.error({
                        title:'文件保存失败',
                        message:result.message
                    })
                }
            }).catch(error => {
                this.loading = false;
                this.$notify.error({
                    title:'文件保存失败',
                    message: error.message
                })
            });
            this.saveVisible = false;
        },
        // 取消分享
        deleteShare(){
            this.$confirm('是否取消分享?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$axios.post(util.API_HOST + '/file/share/delete',[
                    this.shareId
                ]).then(response => {
                    let result = response.data;
                    if(result.code === 200) {
                        this.$router.push('/share/'+this.$route.params.name);
                    }
                }).catch(err => {
                    this.$notify.error({
                        title:'分享取消失败',
                        message:err.message
                    })
                });
            }).catch(err => {});
        },
        myNetPan(){
            let open = window.open('_blank');
            open.location.href = util.WEB_HOST + '/#/main';
        }    
    }
}
</script>

<style scoped>
    #back-icon{
        cursor: pointer;
    }
    #filename{
        cursor: pointer;
    }
    #share-content{
        background-image: linear-gradient(120deg, #89f7fe 0%, #66a6ff 100%);
        width: 100%;
        height: 100vh;
    }
    #share-top {
        font-size: 45px;
        font-weight: 700;
        text-align: center;
    }
    .text {
        font-size: 14px;
    }

    .item {
        margin-bottom: 18px;
    }

    .clearfix:before,
    .clearfix:after {
        display: table;
        content: "";
    }
    .clearfix:after {
        clear: both
    }

    .box-card {
        width: 60%;
        height: 520px;
    }
    #share-main-content{
        margin: auto;
    }
    .box-card{
        margin: auto;
    }
    .block {
        float: left;
        margin: auto;
        font-size: 20px;
        line-height: 50px;
    }

    #unlogin {
        cursor: pointer;
    }
    #unlogin:hover {
        color: rgb(22, 155, 207);
    }
    #shareAvatar {
        cursor: pointer;
    }
    #shareAvatar:hover {
        cursor: pointer;
        box-shadow: rgb(119, 118, 118) 0px 0px 20px ;
    }
    #icon{
        width: 40px;height: 40px;
        float: left;
    }
    #share-title{
        cursor: pointer;
        font-weight: 600;
    }
    #share-title:hover {color: rgb(65, 106, 230);}
    #file-tree{
        border-radius: 5px;
        width: 100%;
        height: 200px;
        overflow: auto;
        border: 1px solid rgba(161, 157, 157, 0.411);
    }
</style>